<template>
  <div class="app-main-content-box">
    <div class="header">
      订单消息
      <el-button
        type="primary"
        size="mini"
        style="float: right"
        @click="onCLickAddItem"
      >新增</el-button>
    </div>
    <div class="table">
      <TablePanel
        ref="OrderMessageTableRef"
        :table-data="tableData"
        :table-head="column"
      >
        <template #businessType="{scope}">
          <span>{{ BUSINESS_TYPE_TEXT[scope.businessType] }}</span>
        </template>
        <template #orderType="{scope}">
          <span>{{
            orderTypeOptions.filter(
              v => v.type === scope.businessType && v.value === scope.orderType
            )[0].label
          }}</span>
        </template>

        <template #ruleType="{scope}">
          <span>订单状态为{{
            orderStateOptions.filter(
              v =>
                v.shop_type === scope.businessType &&
                v.order_type === scope.orderType &&
                v.value === scope.ruleType
            )[0].label
          }}，立即提醒</span>
        </template>

        <template #extraColumn="{scope}">
          {{ getExtraColumnText(scope) }}
        </template>
        <template #broadcastState="{scope}">
          <el-switch
            v-model="scope.broadcastState"
            :active-value="1"
            :inactive-value="0"
            @change="
              onChangeState(scope.id, 'broadcastState', scope.broadcastState)
            "
          />
        </template>
        <template #appState="{scope}">
          <el-switch
            v-model="scope.appState"
            :active-value="1"
            :inactive-value="0"
            @change="onChangeState(scope.id, 'appState', scope.appState)"
          />
        </template>
        <template #bisState="{scope}">
          <el-switch
            v-model="scope.bisState"
            :active-value="1"
            :inactive-value="0"
            @change="onChangeState(scope.id, 'bisState', scope.bisState)"
          />
        </template>
        <template #mpState="{scope}">
          <el-switch
            v-model="scope.mpState"
            :active-value="1"
            :inactive-value="0"
            @change="onChangeState(scope.id, 'mpState', scope.mpState)"
          />
        </template>
        <template #oper="{scope}">
          <el-button
            type="primary"
            size="mini"
            @click="onClickEditItem(scope)"
          >编辑</el-button>
        </template>
      </TablePanel>
      <div v-if="tableData.length > 0" class="pagination fixed">
        <el-pagination
          background
          layout="prev,pager,next,sizes,jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <section>
        <DialogFormData v-if="dialogVisible" ref="formDataRef" />
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onClickSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TablePanel from '@/components/TablePanel'
import {
  BUSINESS_TYPE_TEXT,
  column,
  orderStateOptions,
  orderTypeOptions,
  otherFilesOptions
} from '@/views/msg/orderMessage/config'
import DialogFormData from './components/DialogFormData'
import { addOrderMsgRuleList, changeOrderMsgState, getOrderMsgRuleList, editOrderMsgRule } from '@/api/wxTemplateMsg'

export default {
  name: 'OrderMessage',
  components: { TablePanel, DialogFormData },
  data() {
    return {
      BUSINESS_TYPE_TEXT,
      orderTypeOptions,
      orderStateOptions,
      tableData: [],
      column,
      editForm: {},
      query: {
        page: 1,
        rows: 10
      },
      total: 10,
      dialogVisible: false,
      isEditRule: false,
      dialogTitle: '提示'
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      const res = await getOrderMsgRuleList({
        pageSize: this.query.rows,
        pageNum: this.query.page
      })
      const { data, succeed } = res
      if (succeed) {
        const { list, total } = data
        this.tableData = list
        this.total = total
      }
    },
    // 编辑单条消息--
    onClickEditItem(obj) {
      this.dialogTitle = '编辑'
      this.dialogVisible = true
      this.isEditRule = true
      this.$nextTick(() => {
        const row = JSON.parse(JSON.stringify(obj))
        row.other_files = this.getExtraColumnText(obj).split(',')
        this.$refs.formDataRef.setQuery(row)
      })
    },
    onCLickAddItem() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.isEditRule = false
      this.$nextTick(() => {
        this.$refs.formDataRef.setQuery({
          businessType: 1,
          orderType: '',
          ruleType: '',
          msg: '',
          other_files: []
        })
      })
    },
    handleSizeChange(e) {
      this.query.rows = e
      this.getList()
    },
    handleCurrentChange(e) {
      this.query.page = e
      this.getList()
    },
    onClickSubmit() {
      this.$refs.formDataRef.getQuery().then(res => {
        console.log('得到的表单数据getQuery', res)
        if (res) {
          const api = this.isEditRule ? editOrderMsgRule : addOrderMsgRuleList
          const obj = {
            appState: res.appState,
            bisState: res.bisState,
            broadcastState: res.broadcastState,
            businessType: res.businessType,
            extraColumn: res.extraColumn,
            mpState: res.mpState,
            msg: res.msg,
            orderType: res.orderType,
            ruleType: res.ruleType
          }
          if (this.isEditRule)obj.id = res.id
          api(obj).then(res => {
            if (res.succeed) {
              this.$message.success('成功')
              this.dialogVisible = false
              this.query.page = 1
              this.query.rows = 10
              this.getList()
            }
          })
        }
      })
    },
    getOtherFilesOptions(businessType) {
      return otherFilesOptions.filter(
        v => v.type === businessType
      )
    },
    // 十进制转二进制，得到额外字段的文字
    getExtraColumnText(obj) {
      const { extraColumn, businessType } = obj
      let transExtraColumn = extraColumn.toString(2)
      const len = this.getOtherFilesOptions(businessType).length || 4
      while (transExtraColumn.length < len) {
        transExtraColumn = '0' + transExtraColumn
      }
      const num = transExtraColumn.toString(2).split('')
      const options = otherFilesOptions.filter(v => v.type === businessType)
      const texts = []
      num.map((v, i) => {
        if (Number(v) === 1) {
          texts.push(options[i].label)
        }
      })
      return texts.join(',')
    },
    // 修改状态
    async onChangeState(id, filed, value) {
      console.log('修改状态', filed, value)
      const res = await changeOrderMsgState({
        id,
        [filed]: value
      })
      if (res.succeed) {
        this.$message.success('成功')
        await this.getList()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.pagination {
  width: 100%;
  height: 100px;
  padding: 10px 20px;
  box-sizing: border-box;
  background: #ffffff;
  &.fixed {
    position: fixed;
    right: 0;
    bottom: 0;
  }
}
</style>
